package org.servlet;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.commons.ResultDto;
import org.dao.UserDao;
import org.entity.User;
import org.imple.UserImple;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户登录
 */
@WebServlet("/login.do")
public class LoginServlet extends BaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name") ;
        String pass = req.getParameter("pass") ;

        UserDao dao = new UserImple() ;
        User u = dao.findUser(name,pass) ;

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();


        String json = null ;

        if(u != null){
            ResultDto resultDao = successJson(u,200,"登录成功!") ;
            json = new GsonBuilder().setDateFormat("yyyy-MM-dd")
                    .create().toJson(resultDao) ;
        }else{
            ResultDto resultDao = errorJson("错误的账号或密码！") ;
            json = new Gson().toJson(resultDao) ;
        }
        out.print(json);

        out.flush();
        out.close();
    }
}
